<template>
  <NavBar></NavBar>
  <router-view></router-view>
</template>

<script>
import NavBar from "@/components/NavBar";
import { onMounted } from "@vue/runtime-core";
import jwt_decode from "jwt-decode";
import userApi from "./apis/userApi";
import { useStore } from "vuex";
import router from "@/router/index";
export default {
  name: "app",
  components: {
    NavBar,
  },
  setup() {
    const store = useStore();
    onMounted(() => {
      refreshToken();
    });

    const getLoginInfo = () => {
      const refresh = localStorage.getItem("refresh");
      userApi.tokenRefresh(refresh).then((response) => {
        const access = response.data.access_token;
        localStorage.setItem("access", access);

        store.commit("updateAccess", access);

        let i = jwt_decode(access);
        userApi.getUserInfo(i.sub, access).then((resp) => {
          store.commit("updateUser", resp.data.userinfo);
        });
      });
    };

    const refreshToken = () => {
      const refresh = localStorage.getItem("refresh");

      if (!refresh) {
        router.push({ name: "login" });
        return;
      }

      const reft = jwt_decode(refresh);
      if (reft.exp * 1000 < new Date().getTime()) {
        localStorage.clear();
        router.push({ name: "login" });
        return;
      } else {
        getLoginInfo();
        setInterval(() => {
          getLoginInfo();
        }, 1000 * 60 * 60 * 1.8);
      }
    };
  },
};
</script>

<style>
body {
  background-image: url("https://s.cn.bing.net/th?id=OHR.FalklandKings_ZH-CN6891102487_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&qlt=50");
  align-items: center;
  justify-content: center;
  background-size: cover;
}
</style>
